package persistence

import (
	"todo-gin-server/internal/domain/entity"
	"todo-gin-server/internal/domain/repository"
)

// UserRepositoryImpl 用户仓储实现
type UserRepositoryImpl struct{}

// NewUserRepository 创建用户仓储实例
func NewUserRepository() repository.UserRepository {
	return &UserRepositoryImpl{}
}

// Create 创建用户
func (r *UserRepositoryImpl) Create(user *entity.User) error {
	return DB.Create(user).Error
}

// FindByID 根据ID查找用户
func (r *UserRepositoryImpl) FindByID(id uint) (*entity.User, error) {
	var user entity.User
	err := DB.First(&user, id).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// FindByUsername 根据用户名查找用户
func (r *UserRepositoryImpl) FindByUsername(username string) (*entity.User, error) {
	var user entity.User
	err := DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// FindByEmail 根据邮箱查找用户
func (r *UserRepositoryImpl) FindByEmail(email string) (*entity.User, error) {
	var user entity.User
	err := DB.Where("email = ?", email).First(&user).Error
	if err != nil {
		return nil, err
	}
	return &user, nil
}

// Update 更新用户
func (r *UserRepositoryImpl) Update(user *entity.User) error {
	return DB.Save(user).Error
}

// Delete 删除用户
func (r *UserRepositoryImpl) Delete(id uint) error {
	return DB.Delete(&entity.User{}, id).Error
}